package com.vpen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vpen.blog.common.ReturnResult;
import com.vpen.blog.config.security.JwtTokenUtils;
import com.vpen.blog.entity.User;
import com.vpen.blog.entity.UserLogin;
import com.vpen.blog.mapper.UserMapper;
import com.vpen.blog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Vpen
 * @since 2021-07-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    // 配置文件里有写
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
    * -@author Vpen
    * -@name login
    * -@date 2021/7/8 16:46
    * -@param [userLoginInfo, request]
    * -@return json
    * -@作用: 登录候返回token
    */
    @Override
    public ReturnResult login(UserLogin userLoginInfo, HttpServletRequest request) {
        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(userLoginInfo.getUsername());
//        if (userDetails == null)
//        {
//            return ReturnResult.getInstance().fail("用户不存在.....");
//        }
        if (userDetails != null&&!passwordEncoder.matches(userLoginInfo.getPassword(),userDetails.getPassword())) {
            return ReturnResult.getInstance().fail("用户名或者密码不正确");
        }
        if (!userDetails.isEnabled()){
            return ReturnResult.getInstance().fail("账号不可用");
        }

        CaptchaUtil.clear(request);  // 清除session中的验证码

        // 更新Security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        //放入全局Session
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //生成token
        String token = jwtTokenUtils.generateToken(userDetails);
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
//        tokenMap.put("userInfo",authenticationToken.getPrincipal());

        return ReturnResult.getInstance().success("登录成功",tokenMap);
    }

    /**
     * 作者:Vpen
     * 描述: 根据用户名查找数据库信息
     * */
    @Override
    public User getUserByUserName(String name) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username",name));
    }
}
